import { useCallback, useEffect, useMemo, useState } from 'react'
import { useRecoilValue } from 'recoil'
import { Form, message } from 'antd'
import { ReportReview, TableInfo, WardRate, HospitalParams } from '../data'
import { CardList } from '@/@types'
import { escalationPlatform, getHospitalApplyData, getTableList } from '../service'
import { isNullArray, isNullData } from '@/utils'
import { WordList, getWord } from '@/services/common'
import { userInfo } from '@/store/userInfo'
import { theQuarterData } from '@/store/user'
import { getGoBack } from '@/pages/ReportDetails/service'

export default (): ReportReview => {
  const quarterData = useRecoilValue(theQuarterData)
  const { hospitalCode } = useRecoilValue(userInfo)

  const [rejectForm] = Form.useForm()
  // modal
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  // 卡片信息
  const [cardList, setCardList] = useState<CardList[]>([])

  // 当前选中任务
  const [task, setTask] = useState<Array<string>>(
    isNullArray(quarterData) ? [quarterData[0].value, quarterData![0].children![0].value] : [],
  )
  // 病区
  const [wordList, setWordList] = useState<WordList[]>([])
  // 存放当前选中病区
  const [selectWord, setSelectWord] = useState<number | undefined>()
  // 存放表格数据
  const [tableList, setTableList] = useState<TableInfo[]>([])
  // 存放表格加载效果
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  // echart
  const [chatList, setChatList] = useState<WardRate[]>([])
  // 存放状态
  const [status, setStatus] = useState<string>('')
  // 当前医院信息
  const [hospitals, setHospitals] = useState<HospitalParams | undefined>()
  // 退回id
  const [returnReasonId, setReturnReasonId] = useState<number>()

  // 获取数据
  const getTables = async () => {
    setTableLoading(true)
    const res = await getTableList({
      dataReportYear: task[0] ? task[0] : '',
      dataReportQuarter: task[1] ? task[1] : '',
      hospitalCode,
      wordId: selectWord!,
      status,
    })
    // console.log('res🚀🚀🚀🚀', res)
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setCardList(res.data.dataEscalationHeads)
      setTableList(res.data.dataEscalationBottoms)
      setChatList(res.data.wardRate)
    } else {
      setCardList([])
      setTableList([])
      setChatList([])
    }
    setTableLoading(false)
  }

  const isShowBtn = useMemo(() => {
    if (isNullArray(tableList)) {
      return tableList.every((item) => item.status === '1')
    }
    return false
  }, [tableList])

  // 获取地区
  const getWords = useCallback(async () => {
    const res = await getWord({
      hospitalCode,
      dataReportYear: task[0] ? task[0] : '',
      dataReportQuarter: task[1] ? task[1] : '',
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setWordList(res.data)
      setSelectWord(res.data[0].wordId)
    } else {
      setWordList([])
    }
  }, [task])

  // 退回操作
  const goBack = async (id: number) => {
    setReturnReasonId(id)
    setIsModalOpen(true)
  }

  // 全院退回
  const handleGoBack = async (id: number) => {
    const res = await getGoBack({ id })
    if (isNullData(res) && res.data && isNullArray(res.data) && res.data.success === 200) {
      message.success('退回成功')
      getTables()
    } else {
      message.error(res.data?.message)
    }
  }

  // 关闭modal
  const handleCancelModal = () => {
    setIsModalOpen(false)
    setReturnReasonId(undefined)
    rejectForm.resetFields()
  }

  // 原因提交
  const onFinish = async (values: { returnReason: string }) => {
    const res = await getGoBack({ id: returnReasonId, returnReason: values.returnReason })
    if (isNullData(res) && res.data && isNullArray(res.data) && res.data.success === 200) {
      message.success('退回成功')
      handleCancelModal()
      getTables()
    } else {
      message.error(res.data?.message)
    }
  }

  // 查询当前医院加入时间
  const getApplyData = async () => {
    const res = await getHospitalApplyData({
      hospitalCode,
      dataReportYear: task[0] ? task[0] : '',
      dataReportQuarter: task[1] ? task[1] : '',
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setHospitals(res.data)
    }
    console.log('res🚀🚀🚀🚀', res)
  }

  // 任务下拉框变化时触发
  const handleTaskChange = (e: Array<string>) => {
    setTask(e)
  }

  // 状态下拉框
  const handleStatusChange = useCallback((e: string) => {
    setStatus(e)
  }, [])

  // 病区发生变化时触发
  const handleWordChange = useCallback((e: number) => {
    setSelectWord(e)
  }, [])

  // 上报
  const handleReport = async () => {
    console.log('上报🚀🚀🚀🚀')
    const newlist = tableList.map((item) => item.dataId)
    const res = await escalationPlatform({
      ids: newlist,
    })
    console.log('res🚀🚀🚀🚀', res)
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      message.success('上报成功')
      getTables()
      getApplyData()
    } else {
      message.error('操作失败')
    }
  }

  // 判断是否可以展示上报省平台
  // const isShowBtnHospital = useMemo(() => {
  //   const info = tableList.find((item) => item.wardName === '全院')
  //   if (info) {
  //     return info.isProceed === 1
  //   }
  //   return false
  // }, [tableList])

  useEffect(() => {
    console.log('status🚀🚀🚀🚀', status, selectWord)
    if (selectWord !== undefined) {
      // console.log('我发给撒🚀🚀🚀🚀')
      getTables()
    }
  }, [selectWord, status, task])

  useEffect(() => {
    getApplyData()
    getWords()
  }, [task])

  // useEffect(() => {

  // }, [])

  return {
    cardList,
    handleTaskChange,
    handleStatusChange,
    task,
    tableList,
    tableLoading,
    status,
    handleReport,
    selectWord,
    handleWordChange,
    wordList,
    chatList,
    goBack,
    isShowBtn,
    hospitals,
    isModalOpen,
    handleCancelModal,
    rejectForm,
    onFinish,
    handleGoBack,
    // isShowBtnHospital,
  }
}
